/**
 * Created by henian.xu on 2020/2/6.
 * 混合此对象必须实现 actions.update 方法
 */
import { assert, hasOwn } from '@/utils';

const mixin = {
  state: {
    rawData: null,
  },
  getters: {
    rawData(state) {
      if (state.rawData === null) this.dispatch('update');
      // console.log(this);
      return state.rawData;
    },
  },
  mutations: {
    _setRawData(state, data) {
      state.rawData = data;
    },
  },
};
export default (options = {}) => {
  return Object.keys(mixin).reduce((pre, cur) => {
    const res = pre;
    const option = res[cur];
    if (!option) {
      res[cur] = mixin[cur];
    } else {
      // TODO 暂时不考虑 option 为函数的情况(比如 state 是个函数时),当用到时再补上。
      const mixinOption = mixin[cur];
      Object.keys(mixinOption).forEach((key) => {
        assert(
          !hasOwn(option, key),
          `${cur}.${key} 属性已经存在,无法混合`,
          `store.rawDataMixin`,
        );
        option[key] = mixinOption[key];
      });
    }
    return res;
  }, options);
};
